//
//  view1.m
//  shanglv51
//
//  Created by Darker on 2017/1/9.
//  Copyright © 2017年 shanglv. All rights reserved.
//

#import "SSSSelectedBusinessView.h"
#import "selectBusinessCell.h"
#import "SSSSelectedBussinessModel.h"
#import "SSSBusinessModel.h"

static NSString *strBusinessID    = @"editViewCellID";


@interface SSSSelectedBusinessView ()<UITableViewDelegate,UITableViewDataSource>
{
    
    BOOL     _clean;
    NSInteger _currentPage;
    //NSMutableArray *_dataArray;
    NSMutableArray  *_businessArray;
    
}

//内容视图
@property (nonatomic, strong) UIView  *contentView;

//titleLbel
@property (nonatomic, strong) UILabel  *label1;

//蓝色的view
@property (nonatomic, strong) UIView  *lineView;

//行业tableView
@property (nonatomic, strong) UITableView  *buttomTableView;


/** 请求参数 */
@property(nonatomic, strong) NSMutableDictionary *parameter;

@end

@implementation SSSSelectedBusinessView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self layoutAllSubviews];
        self.isMultiselect = NO;
        //请求店铺数据
        [self reloadBussinessData];
    }
    return self;
}
- (void)layoutSubviews{
    
    //[super layoutSubviews];
    
//    [self layoutAllSubviews];
//    [self reloadBussinessData];
}
- (void)reloadBussinessData{
    
    
        ZDRefreshHeader *header = [ZDRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // 马上进入刷新状态
        [header beginRefreshing];
        // 设置header
        _buttomTableView.mj_header = header;
    
        // 上拉加载
        _buttomTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
}
- (void)loadNewData{
    
    [_buttomTableView.mj_footer endRefreshing];
    _currentPage = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"currentPage"] = @(_currentPage);
    params[@"pageSize"] = @"20";
    self.parameter = params;
    
    [[XHRequestManager manager] getRequest:kConfigPath(kSelectedBusiness) params:params success:^(id  _Nonnull responseObj) {
        
        XHLog(@"-----%@----",responseObj);
        if ([responseObj[@"status"] intValue] == 0){
            
            [_businessArray removeAllObjects];
            
            if ([responseObj[@"data"][@"pageList"] count] == 0) {
                
                showTipHudStr(@"暂无数据");
                [_buttomTableView.mj_header endRefreshing];
                
                return ;
            }
            
            //_dataArray = [SSSRecommendModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"][@"pageList"]];
            
            NSArray *array = [SSSSelectedBussinessModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"][@"pageList"]];
            _businessArray = [NSMutableArray array];
            [_businessArray addObjectsFromArray:array];
            
            //不是最后一次请求
            if (self.parameter != params) return ;
            //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //刷新表格
                [_buttomTableView reloadData];
                
            });
            
            [_buttomTableView.mj_header endRefreshing];
            
            //_listTableView.mj_footer.hidden = (_currentPage == 1);
            
            if ([responseObj[@"data"][@"hasNextPage"] intValue] == 0) {
                
                [_buttomTableView.mj_footer endRefreshingWithNoMoreData];
                
            }else{
                
                [_buttomTableView.mj_header endRefreshing];
            }
            
        }else{
            
            showTipHudStr(kResponseMessage);
            [_buttomTableView.mj_header endRefreshing];
        }
        
        
    } failure:^(NSError * _Nonnull error) {
        
        showTipHudStr(error.localizedDescription);
        [_buttomTableView.mj_header endRefreshing];
        
    }];
    
    
}
- (void)loadMoreData{
    
    [_buttomTableView.mj_header endRefreshing];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"currentPage"] = @(++_currentPage);
    params[@"pageSize"] = @"20";
    [_businessArray removeAllObjects];
    self.parameter = params;
    
    [[XHRequestManager manager] getRequest:kConfigPath(kSelectedBusiness) params:params success:^(id  _Nonnull responseObj) {
        
        XHLog(@"-----%@",responseObj);
        if ([responseObj[@"status"] intValue] == 0){
            
            NSArray *array = [SSSSelectedBussinessModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"][@"pageList"]];
            [_businessArray addObjectsFromArray:array];
            
            //不是最后一次请求
            if (self.parameter != params) return ;
            //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //刷新表格
                [_buttomTableView reloadData];
                
            });
            
            [_buttomTableView.mj_header endRefreshing];
            
            //_listTableView.mj_footer.hidden = (_currentPage == 1);
            
            if ([responseObj[@"data"][@"hasNextPage"] intValue] == 0) {
                
                [_buttomTableView.mj_footer endRefreshingWithNoMoreData];
                
            }else{
    
                [_buttomTableView.mj_header endRefreshing];
            }
            
            
        }else{
            
            showTipHudStr(kResponseMessage);
            [_buttomTableView.mj_header endRefreshing];
        }
        
        
    } failure:^(NSError * _Nonnull error) {
        
        showTipHudStr(error.localizedDescription);
        [_buttomTableView.mj_header endRefreshing];
        
    }];

    
}


//实现block
- (void)returnText:(ReturnTextBlock)block {
    self.returnTextBlock = block;
}

- (void)layoutAllSubviews{
    
    /*创建灰色背景*/
    UIView *bgView = [[UIView alloc] initWithFrame:self.frame];
    bgView.backgroundColor = [[UIColor colorWithHex:@"000000"] colorWithAlphaComponent:0.3];
    [self addSubview:bgView];
    
    /*添加手势事件,移除View*/
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView:)];
    [bgView addGestureRecognizer:tapGesture];
    
    /*创建显示View*/
    _contentView = [[UIView alloc] init];
    _contentView.frame = CGRectMake(0, HeigthIos6CompeteWithCurrent(382), self.frame.size.width,self.frame.size.height - HeigthIos6CompeteWithCurrent(382));
    _contentView.backgroundColor=[UIColor whiteColor];
    _contentView.layer.cornerRadius = 4;
    _contentView.layer.masksToBounds = YES;
    [self addSubview:_contentView];
    
    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor colorWithHex:@"F0F0F0"];
    [_contentView addSubview:headerView];
    headerView.frame = CGRectMake(0, 0, KSCREEN_Width, HeigthIos6CompeteWithCurrent(30));
    
    
    /*可以继续在其中添加一些View*/
    _label1 = [[UILabel alloc]initWithFrame:CGRectMake(WidthIos6CompeteWithCurrent(16), 5, 200, HeigthIos6CompeteWithCurrent(20))];
//               WithFrame:CGRectMake(WidthIos6CompeteWithCurrent(20), HeigthIos6CompeteWithCurrent(10), self.frame.size.width - WidthIos6CompeteWithCurrent(100), HeigthIos6CompeteWithCurrent(20))];
    _label1.text = @"请选择店铺";
    _label1.font = [SSSFont systemFontOfSize:12];
    [_label1 setTextColor:[UIColor colorWithHex:@"999999"]];
    _label1.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:_label1];
    
//    _label1.sd_layout
//    .centerYEqualToView(headerView)
//    .leftSpaceToView(headerView,WidthIos6CompeteWithCurrent(16))
//    .widthIs(WidthIos6CompeteWithCurrent(200))
//    .heightIs(HeigthIos6CompeteWithCurrent(20));
    
    
    //蓝色的线
    _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, HeigthIos6CompeteWithCurrent(30),  self.frame.size.width, 1)];
    _lineView.backgroundColor = [UIColor colorWithHex:@"46B77D"];
    [_contentView addSubview:_lineView];
    
    //初始化数据源
//     _businessArray = [NSArray arrayWithObjects:@"农、林、牧、渔业",@"采矿业",@"食品、饮料",@"纺织、服装、皮毛",@"木材、家具",@"造纸、印刷",@"石油、化学、塑料、塑胶",@"电子",@"金属、非金属",@"机械、设备、仪表",@"医药、生物制品",@"其他制造业",@"电力、热力、燃气及水生产和供应业",@"建筑业",@"批发和零售业",@"交通运输、仓储和邮政业",@"住宿和餐饮业",@"金融业",@"房地产业",@"租赁和商务服务业",@"科学研究和技术服务业",@"水利、环境和公共设施管理业",@"居民服务、修理和其他服务业",@"教育",@"文化、体育和娱乐业",@"公共管理、社会保障和社会组织",@"国际组织", nil];
    
    _buttomTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, HeigthIos6CompeteWithCurrent(31), self.frame.size.width, _contentView.frame.size.height - HeigthIos6CompeteWithCurrent(31)) style:UITableViewStylePlain];
    _buttomTableView.delegate = self;
    _buttomTableView.dataSource = self;
    _buttomTableView.backgroundColor = [UIColor clearColor];
    _buttomTableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    [_buttomTableView registerNib:[UINib nibWithNibName:@"selectBusinessCell" bundle:nil] forCellReuseIdentifier:strBusinessID];
    [_contentView addSubview:_buttomTableView];
    
}
#pragma amrk - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _businessArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return HeigthIos6CompeteWithCurrent(50);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    selectBusinessCell  *cell = [tableView dequeueReusableCellWithIdentifier:strBusinessID];
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:strBusinessID forIndexPath:indexPath];
    }
    cell.model = _businessArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //如果选中行业之后第二次进入的时候选中的显示亮图
//    if ([cell.businessNameLbel.text isEqualToString:self.ClickString]) {
//        cell.selectedImageView.image = [UIImage imageNamed:@"duigou2"];
//    }else{
//        cell.selectedImageView.image = [UIImage imageNamed:@"duigou1"];
//    }
   // _clean = YES;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.buttomTableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SSSSelectedBussinessModel *model = _businessArray[indexPath.row];
    SSSBusinessModel *buModel = [[SSSBusinessModel alloc]init];
    buModel.businessID = model.businessID;
    
//    NSArray *array = [tableView visibleCells];
//    for (selectBusinessCell *cell in array) {
//        //没选中显示暗图
//        cell.selectedImageView.image =  [UIImage imageNamed:@"duigou1"];
//    }
//    //选中显示亮图
//    selectBusinessCell *cell = [self.buttomTableView cellForRowAtIndexPath:indexPath];
//    cell.selectedImageView.image = [UIImage imageNamed:@"duigou2"];
    
    NSString *str = model.bName;
    //block传值
    if (self.returnTextBlock != nil) {
        self.returnTextBlock(str);
    }
//
    [self dismissContactView];
}
#pragma mark - 手势点击事件,移除View
- (void)dismissContactView:(UITapGestureRecognizer *)tapGesture{
    
    [self dismissContactView];
}
-(void)dismissContactView
{
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.alpha = 0;
    } completion:^(BOOL finished) {
        [weakSelf removeFromSuperview];
    }];
}
// 这里加载在了window上
-(void)showView

{
    UIWindow * window = [UIApplication sharedApplication].windows[0];
    [window addSubview:self];
}
//- (NSMutableArray *)businessArray{
//    
//    if (!self.businessArray) {
//        self.businessArray = [NSMutableArray array];
//    }
//    return self.businessArray;
//}

@end
